package admin

import (
	"fmt"
	"strings"
	"time"
	"yunj/pkg/global"
	"yunj/pkg/yunj/app/service/admin/logservice"
	errcodeEnum "yunj/pkg/yunj/core/enum/errcode"
	"yunj/pkg/yunj/core/response"
	"yunj/pkg/yunj/util"

	"github.com/gin-gonic/gin"
)

// 捕获panic
func Recover(ctx *gin.Context, recovered any) {
	var err error
	if rErr, ok := recovered.(error); ok {
		err = rErr
	} else {
		err = fmt.Errorf("%v", recovered)
	}
	fmt.Printf("全局panic错误捕获%T：%v", recovered, recovered)
	uri := ctx.Request.RequestURI
	// 判断是否后台请求
	if strings.HasPrefix(uri, global.Config.GetAppAdminEntrance()) {
		// 日志记录
		appendArgs := logservice.AppendArgs{
			EndTime:         time.Now().In(time.Local), // 计算耗时
			ResponseContent: util.FormatError(err),
		}
		logservice.Record(ctx, appendArgs)
		// 是否跳转到提示页
		if !util.IsAsync(ctx) && !strings.HasPrefix(uri, "/tips") {
			util.RedirectAdminTips(ctx, errcodeEnum.ERROR, err.Error())
		}
	} else {
		// 文件错误日志记录
		global.Logger.Error(util.FormatError(err))
	}
	response.FailJsonData(err.Error()).Response(ctx)
	ctx.Abort()
}
